<script setup>

import Card from "@/componets/Card.vue";
import {Message, Notebook, Refresh, Select, User} from "@element-plus/icons";
import {useStore} from "@/store/index.js";
import {computed, ref} from "vue";
import {reactive} from "vue";
import {accessHeader, get, post} from "@/net/index.js";
import {ElMessage} from "element-plus";
import axios from "axios";

const store = useStore();

const registerTime = computed(() => {
    return new Date(store.user.registerTime).toLocaleString();
})

const desc = ref('');
const baseFormRef = ref();
const emailFormRef = ref();

const baseForm = reactive({
    username: '',
    gender: '1',
    phone: '',
    qq: '',
    wx: '',
    desc: ''
})

const emailForm = reactive({
    email: '',
    code: ''
})

const validateUsername = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入用户名'));
    } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
        callback(new Error("用户名不能包含特殊字符"));
    } else {
        callback();
    }
};

const rules = {
    username: [
        {validator: validateUsername, trigger: ['blur', 'change']},
    ],
    email: [
        {required: true, message: "请输入合法的电子邮件地址件", trigger: 'blur'},
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
    ],
    code: [
        {required: true, message: "请输入验证码", trigger: 'blur'},
    ]
};

const loading = reactive({
    form: true,
    base: false
})

function saveDetails() {
    baseFormRef.value.validate(isValid => {
        if (isValid) {
            loading.base = true;
            post('/api/user/sava-details', baseForm, () => {
                ElMessage.success('保存成功');
                store.user.username = baseForm.username;
                desc.value = baseForm.desc;
                loading.base = false
            }, (message) => {
                ElMessage.error(message);
                loading.base = false
            })
        }
    })
}

get('api/user/details', data => {
    baseForm.username = store.user.username
    baseForm.gender = data.gender
    baseForm.phone = data.phone
    baseForm.qq = data.qq
    baseForm.wx = data.wx
    baseForm.desc = data.desc
    desc.value = data.desc
    emailForm.email = store.user.email
    loading.form = false
})

function sendEmailCode() {
    get(`api/auth/ask-code?email=${emailForm.email}&type=modify`, () => {
        ElMessage.success('验证码已发送，请查收');
    }, (message) => {
        ElMessage.error(message);
    })
}

function modify() {
    post("api/user/modify-email", emailForm, () => {
        ElMessage.success('修改成功');
        store.user.email = emailForm.email;
    }, (message) => {
        ElMessage.error(message);
    })
}

function beforeAvatarUpload(rawFile) {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('只能上传jpg或png格式的图片');
        return false;
    } else if (rawFile.size / 1024 > 100) {
        ElMessage.error('图片大小不能超过100KB');
        return false;
    } else {
        return true;
    }
}

function uploadSuccess(response) {
    ElMessage.success('上传成功');
    store.user.avatar = response.data;
}
</script>

<template>
    <div style="display: flex; max-width: 950px; margin: auto">
        <div class="settings-left">
            <card v-loading="loading.form" :icon="User" desc="在这里编辑您的个人信息" title="账户信息设置">
                <el-form ref="baseFormRef" :model="baseForm" :rules="rules" label-position="top"
                         style="margin: 0 10px 10px 10px">

                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="baseForm.username"></el-input>
                    </el-form-item>

                    <el-form-item label="性别">
                        <el-radio-group v-model="baseForm.gender">
                            <el-radio :label="0">男</el-radio>
                            <el-radio :label="1">女</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="baseForm.phone"></el-input>
                    </el-form-item>

                    <el-form-item label="QQ号" prop="qq">
                        <el-input v-model="baseForm.qq"></el-input>
                    </el-form-item>

                    <el-form-item label="微信号" prop="wx">
                        <el-input v-model="baseForm.wx"></el-input>
                    </el-form-item>

                    <el-form-item label="个人简介" prop="desc">
                        <el-input v-model="baseForm.desc" :rows="6" type="textarea"></el-input>
                    </el-form-item>
                    <div>
                        <el-button :icon="Select" :loading="loading.base" type="success" @click="saveDetails">
                            保存用户信息
                        </el-button>
                    </div>
                </el-form>
            </card>

            <card :icon="Message" desc="可以修改默认绑定的邮件地址" style="margin-top: 10px" title="电子邮件设置">
                <el-form ref="emailFormRef" :model="emailForm" :rules="rules">
                    <el-form-item label="电子邮件" prop="email">
                        <el-input v-model="emailForm.email"></el-input>
                    </el-form-item>

                    <el-form-item prop="code">
                        <el-row :gutter="10" style="width: 100%">
                            <el-col :span="18">
                                <el-input v-model="emailForm.code" placeholder="请输入验证码"></el-input>
                            </el-col>
                            <el-col :span="6">
                                <el-button plain style="width: 100%" type="success" @click="sendEmailCode">获取验证码
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                </el-form>
                <div>
                    <el-button :icon="Refresh" type="success" @click="modify">更新电子邮件</el-button>
                </div>
            </card>
        </div>

        <div class="setting-right">
            <div style="position: sticky; top: 20px;">

                <card>
                    <div style="text-align: center; padding: 5px 15px 0 15px">
                        <div>
                            <el-avatar :size="70" :src="store.avatarUrl"/>
                            <div style="margin: 5px 0;">
                                <!--                自动发起post请求-->
                                <el-upload :action="axios.defaults.baseURL + '/api/image/avatar'"
                                           :before-upload="beforeAvatarUpload"
                                           :headers="accessHeader()"
                                           :on-success="uploadSuccess"
                                           :show-file-list="false">
                                    <el-button round size="small">修改头像</el-button>
                                </el-upload>
                            </div>
                            <div style="font-weight: bold">您好，{{ store.user.username }}</div>
                        </div>
                        <el-divider style="margin: 10px 0"/>
                        <div style="font-size: 14px; color: grey; padding: 10px">
                            {{ desc || '这个用户很懒，还没有自我介绍' }}
                        </div>
                    </div>
                </card>

                <card style="margin-top: 10px; font-size: 14px">
                    <div>
                        账户注册时间：{{ registerTime }}
                    </div>

                    <div style="color: grey">
                        欢迎加入我们的学习论坛
                    </div>

                </card>
            </div>
        </div>
    </div>
</template>

<style scoped>

.settings-left {
    flex: 1;
    margin: 20px;
}

.setting-right {
    width: 300px;
    margin: 20px;
}

</style>